package com.EJ.ejcompanyweb;

import android.Manifest;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.EJ.ejcompanyweb.Util.GetRxPermissions;
import com.EJ.ejcompanyweb.entity.ItemEntity;
import com.bumptech.glide.Glide;
import com.bun.miitmdid.core.JLibrary;
import com.dm.sdk.ads.splash.SplashAD;
import com.dm.sdk.common.util.AdError;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;

import update.UpdateAppUtils;

import com.bun.miitmdid.core.JLibrary;
import com.dm.sdk.ads.splash.SplashAD;
import com.dm.sdk.ads.splash.SplashAdListener;
import com.dm.sdk.common.util.AdError;

public class LoadActivity extends AppCompatActivity implements SplashAdListener {
    private String TAG=this.getClass().getSimpleName();
    private ImageView imageView;
    private ArrayList<ItemEntity> itemEntities = new ArrayList<ItemEntity>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        //隐藏状态栏
        int flag= WindowManager.LayoutParams.FLAG_FULLSCREEN;
        //获得当前窗体对象
        Window window=LoadActivity.this.getWindow();
        //设置当前窗体为全屏显示
        window.setFlags(flag, flag);
        getWindow().getDecorView().setSystemUiVisibility(View.INVISIBLE);
        getSupportActionBar().hide();
        setContentView(R.layout.activity_splash_domob);

/*        //权限申请
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.INTERNET},10);
        }
        */
        new GetRxPermissions(this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.INTERNET}).StartRequestPermissions();

        try {
            synchronized (itemEntities) {
                new JsoupTaskThread().start();
            }
        }catch (Exception e){
            //Toast.makeText(this,"无法连接到Web服务器，请查看网络",Toast.LENGTH_LONG);
            Log.e(TAG,"无法连接到Web服务器，请查看网络");
        }
        UpdateAppUtils.getInstance().deleteInstalledApk();
        hideSystemNavigationBar();
/*
        imageView=findViewById(R.id.ImageView);
       //使用Glide设置网络图片
        Glide.with(LoadActivity.this)
                .load(url)
                .diskCacheStrategy(DiskCacheStrategy.ALL)//本地缓存策略
                .skipMemoryCache(true)//是否进行内存缓存
                .priority(Priority.IMMEDIATE)//加载优先级
                .crossFade()
                .dontAnimate()
                .into(imageView);
*/

    }
    private   void activityStart() {
        Intent intent = new Intent(this, MainActivity.class);
        intent.putExtra("itemEntities",(ArrayList<ItemEntity>)itemEntities);
        startActivity(intent);
        finish();
    }
    /**
     * 获取网站数据
     */
    private class JsoupTaskThread extends Thread{
            private String root_url = getString(R.string.root_url);
            @Override
            public void run () {
            Document doc = null;
            try {
                doc = Jsoup.connect(root_url).get();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (doc != null) {
                Elements div = doc.select("div.side-inner");
                Elements lis = div.select("li");
                ArrayList<ItemEntity> al2 = new ArrayList<ItemEntity>();
                for (Element element : lis) {
                    String titic = element.text();
                    String url1 = element.select("a").attr("href");
                    String Url="http://www.chinaags.net/"+url1;
                    al2.add(new ItemEntity(titic, Url));
                }
                al2.remove(0);
                al2.remove(0);
                al2.remove(al2.size()-1);
                for (ItemEntity i : al2) {
                    //拿到 状态栏上的 物资名称和url
                    Log.e(TAG, i.toString());
                }
                itemEntities = al2;
            }
        }
    }

    /**
     * 开屏页一定要禁止用户对返回按钮的控制，否则将可能导致用户手动退出了App而广告无法正常曝光和计费
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_HOME) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private SplashAD splashAD;
    private boolean canJump = false;
    private Handler handler = new Handler(Looper.getMainLooper());
    //隐藏NavigationBar(
    private void hideSystemNavigationBar() {
        overridePendingTransition(0, 0);
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) {
            View view = this.getWindow().getDecorView();
            view.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN;
            decorView.setSystemUiVisibility(uiOptions);
        }
        JLibrary.InitEntry(getBaseContext());
        ViewGroup contentView = this.findViewById(R.id.splash_container);
        //此为测试的appKey 和 代码位
        splashAD = new SplashAD(this, getString(R.string.AppKey), getString(R.string.CodeId), this, 40000);
        splashAD.fetchAndShowIn(contentView);
    }

    @Override
    public void onAdDismissed() {
        Log.d("dp", "点击了跳转按钮");
        //手数太快会造成，拿不到Web数据（存在Bug）
        for (ItemEntity i:itemEntities){
            //拿到 状态栏上的 物资名称和url
            Log.e(TAG,i.toString());
        }
        activityStart();
        this.finish();
    }

    @Override
    public void onNoAd(AdError error) {
        //此方法主要是防止在拉取开屏广告时出错导致开屏一闪而过，开发者也可以根据自己的需求自己实现，不一定按照此方式实现
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                for (ItemEntity i:itemEntities){
                    //拿到 状态栏上的 物资名称和url
                    Log.e(TAG,i.toString());
                }
                activityStart();
                LoadActivity.this.finish();
            }

        }, 4000);
        Log.d("dp", error.getErrorMsg() + "  " + error.getErrorCode());//具体错误码参考在下方
    }

    @Override
    public void onAdPresent() {
        Log.d("dp", "展现了");
    }

    @Override
    public void onAdClicked() {
        Log.d("dp", "点击页面内容");
    }

    @Override
    public void onAdFilled() {
        Log.d("dp", "下发广告了");
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (canJump) {
            this.finish();
        }
    }
    @Override
    protected void onPause() {
        super.onPause();
        canJump = true;
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        // Glide.get(this).clearMemory();//清除内存缓存
        handler.removeCallbacksAndMessages(null);

    }
}
